<?php

/**

 * 积分充值管理

 */

class AdminPayLogController extends AdminBaseController {

	/**

	 * 自动执行

	 */

	public function _initialize() {

		parent::_initialize();

		$this->db = model('Pay');

	}

	/**

	 * 会员财务管理

	 */

	public function index() {

		$type   = isset($_GET['type']) ? intval($_GET['type']) : 0 ;

		if (IS_POST || isset($_GET['act'])) {

			//分页

			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;

			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;

			$sqlmap = array();

			$sqlmap['type'] = $type;

	    	if ($_GET['keyword']) {

	    		$map = array();

	    		$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");

	    		$ids = model('user')->where($map)->getField('id',TRUE);

	    		if (empty($ids)) $sqlmap['user_id'] = array('IN','');

            	else  $sqlmap['user_id'] = array('IN',$ids);

	    	}

	        if (isset($_GET['pay_status']) && $_GET['pay_status'] != '') {

	            $sqlmap['status'] = intval($_GET['pay_status']);

	        }

            if (isset($_GET['stime']) && !empty($_GET['stime']) && isset($_GET['etime']) && !empty($_GET['etime'])) {

                $stime = strtotime($_GET['stime']);

                $etime = strtotime($_GET['etime']);

                $sqlmap['dateline'] = array(

                    array('gt',$stime),

                    array('lt',$etime),

                );

            }

			if (isset($_GET['act']) && $_GET['act'] == 'excel') {

				if($type == 0){

					$headerTitle = array(

						'username'=>'会员昵称',

						'trade_sn'=>'单号',

						'status'  => '支付状态',

						'eth_nums'=>'ETH数量',

						'eth_address'=>'ETH地址',

						'dateline'=>'申请时间',

					);

				} else {

					$headerTitle = array(

						'username'=>'会员昵称',

						'trade_sn'=>'外网单号',

						'status'  => '支付状态',

						'eth_nums'=>'转入数量',

						'dateline'=>'申请时间',

					);

				}



				$list = $this->db->where($sqlmap)->order("id desc");

				self::DownloadCSV($list,$headerTitle);exit;

			}

			$data = array();

			$infos = $this->db->where($sqlmap)

			->order('id DESC')->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])->select();

	    	foreach ($infos as $k => $info) {

	    		$info['username'] = get_nickname($info['user_id']);

	    		$infos[$k] = $info;

	    	}

            $money = $this->db->where($sqlmap)->sum('eth_nums');

            $money = empty($money)?0:$money;

            $data['title'] = '统计概览：累计数量 '.$money;

	    	$data['rows']  = (array) $infos;

	    	$data['total'] = (int) $this->db->where($sqlmap)->count();

	    	$status_config = array(

	    		array('id'=>'0','name'=>'待审核'),

	    		array('id'=>'1','name'=>'通过'),

	    		array('id'=>'2','name'=>'驳回'),

	    	);

	    	$data['status'] = $status_config;

			$data['search']['status_txt'] = isset($_GET['pay_status']) ? $_GET['pay_status'] :'';

			echo json_encode($data);

		}else {

			include $this->admin_tpl('admin_pay_log'.$type);

		}

	}

	private function DownloadCSV($selectObject,$head,$config){

		$fileName=time();

		if ( !is_object( $selectObject ) || !is_array( $head ) ) {

			exit('参数错误!');

		}

		set_time_limit(0);

		//下载头.

		header ('Content-Type: application/vnd.ms-excel;charset=gbk');

		header ('Content-Disposition: attachment;filename="'.$fileName.'.csv"');

		header ('Cache-Control: max-age=0');

		//输出流;

		$file = 'php://output';

		$fp = fopen ( $file, 'a' );



		function changCode( $changArr ) {

			// 破Excel2003中文只支持GBK编码;

			foreach ( $changArr as $k => $v ) {

				$changArr [$k] = iconv ( 'utf-8', 'gbk', $v );

			}

			//返回一个 索引数组;

			return array_values( $changArr );

		};

		//写入头部;

		fputcsv ( $fp, changCode( $head ) );

		//写入数据;

		$pageSize = 100;//每次查询一百条;

		$page  = 1;//起始页码;

		$list = array();

		$status_config = array('待审核','通过','驳回');

		$cloneObj = clone $selectObject;//因为thinkphp内部执行完select方法后会清空对象属性,所以clone;

		while ( $list = $cloneObj ->limit( $pageSize*( ($page++)-1 ), $pageSize )->select()  ) {

			$cloneObj = clone $selectObject;

			//对查询结果二次处理

			foreach ( $list as $key => $value ) {

				$value['dateline'] = date('Y-m-d H:i',$value['dateline']);

				$value['username'] = get_nickname($value['user_id']);

				$value['trade_sn'] = '`'.$value['trade_sn'];

				$value['status']   = $status_config[$value['status']];

				$value = array_intersect_key( $value, $head );//返回需要写入CSV的数据;

				$value = array_merge( $head, $value );//利用此函数返回需要的顺序;

				$value = changCode( $value );

				fputcsv ( $fp, $value );//写入数据;

				flush();

			}

			ob_flush();

		}

		exit();

	}

	/**

	 * 审核处理

	 * @return [type] [description]

	 */

	public function edit_pay(){

		if(IS_POST)	{

			$_paystatus = intval($_POST['status']);

			$_dealinfo  = trim($_POST['deal_info']);

			$_payId = intval($_POST['id']);

			if (!in_array($_paystatus, array(1,2))) {

				showmessage('请忽非法提交');

			}

			if (empty($_dealinfo)) showmessage('请填写处理意见');

			$pay_infos = $this->db->where(array('id'=>$_payId))->find();

			if (empty($pay_infos) || $pay_infos['status'] > 0 ) {

				showmessage('参数错误或已处理');

			}

			try {

				$this->db->startTrans();

				$updateArray = array();

				$updateArray['status'] = $_paystatus;

				$updateArray['deal_info'] = $_dealinfo;

				$updateArray['deal_time'] = NOW_TIME;

				$updateArray['deal_admin'] = session('ADMIN_ID');

				$update_result = $this->db->where(array('id'=>$_payId))->save($updateArray);

				if (!$update_result) {

					throw new Exception("处理失败");

				}

				if ($_paystatus == 1) {

					if($pay_infos['type'] == 0) {

						$member = model('user')->field('pay_points,freeze_points')->where(array('id'=>$pay_infos['user_id']))->find();

						//通过审核自动转化积分

						$update_user = model('user')->where(array('id' => $pay_infos['user_id']))->setInc('pay_points',$pay_infos['eth_integral']);

						$insert_array = array();

						$insert_array['user_id'] = $pay_infos['user_id'];

						$insert_array['av_points'] = $pay_infos['eth_integral'];

						$insert_array['freeze_points'] = 0 ;

						$insert_array['descript'] = '在线充值'.$pay_infos['eth_integral'].'积分';

						$insert_array['dateline'] = NOW_TIME;

						$insert_array['now_points'] = $member['pay_points'] + $pay_infos['eth_integral'];

						$insert_array['now_freeze_points'] = $member['freeze_points'];

						$insert_array['av_type'] = 2;

						$insert = model('UserPointslog')->add($insert_array);

						if ($insert === false || $update_user === false) {

							throw new Exception("处理失败");

						}

					} else if($pay_infos['type'] == 1) {

						//BLA

						$member = model('user')->field('user_money,freeze_money')->where(array('id'=>$pay_infos['user_id']))->find();

						//通过审核自动转化积分

						$update_user = model('user')->where(array('id' => $pay_infos['user_id']))->setInc('user_money',$pay_infos['eth_integral']);

						$insert_array = array();

						$insert_array['user_id'] = $pay_infos['user_id'];

						$insert_array['av_amount'] = $pay_infos['eth_integral'];

						$insert_array['freeze_amount'] = 0 ;

						$insert_array['msg'] = '在线充值'.$pay_infos['eth_nums'].'ETH币';

						$insert_array['dateline'] = NOW_TIME;

						$insert_array['now_amount'] = $member['user_money'] + $pay_infos['eth_integral'];

						$insert_array['now_freeze_amount'] = $member['freeze_money'];

						$insert_array['msg_type'] = 6;

						$insert = model('UserMoneylog')->add($insert_array);

						if ($insert === false || $update_user === false) {

							throw new Exception("处理失败");

						}

						

					}

				}

				$this->db->commit();

				showmessage('处理成功',U('index',array('type'=>$pay_infos['type'])),1);

			} catch (Exception $e) {

				$this->db->rollback();

				showmessage($e->getMessage(),U('index',array('type'=>$pay_infos['type'])));

			}

		} else {

			showmessage('请忽非法提交');

		}

	}

}